package com.lightsh.webview;

import com.lightsh.utility.R;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class JsWebView extends WebView{
	
	private static final String TAG = "JsWebView";

	public JsWebView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	public JsWebView(Context context, AttributeSet attrs){
		super(context, attrs);
	}
	
	public void startTest(){
		enableJs();
		loadData("", "text/html", "utf-8");
		loadUrl("javascript:window.Client.fillProfileSuccess();");
		
//		loadUrl("https://openapi.360.cn/oauth2/authorize?client_id=33973d634f9d6f40aa980c0624fef9ef&response_type=token&redirect_uri=oob&scope=basic&display=default");		
//		loadUrl("file:///android_asset/demo.html");
//		loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/demo.html");
//		loadUrl("http://www.baidu.com");
//		loadUrl("https://passport.360.cn/api.php?parad=0QGmq0PRqusDg3rdaC26YXLc18Ckoi0OG2Y9qSMEwEIEzEMwyvikZ79%2FC88yOqJS2epPFumusvk7V4d23Gu08avrY7TkX1ekOz4Ov6cqiHr7j9oFvNRlsazttBq%2FoqPWYoeoQFv9A%2BYsjt2JxR7bdH%2Fb0G9AzXyRSQaoeejGSwXeoxLxu6PXdUbxECaE3zjxyVB495RGgokvsGEfc0pwzrjo%2FK1%2Bojp4XRaXDeFr%2FM7gBjJDNjrpoMz8tFfOSE7bsm2oqFlUcbjWj%2FBUfieglazL8WMlmujGJNBE2tgCicTBDcTaaLP3%2Bry3D%2BCDzj0EiO4csRxWOTdWf2OxNg4WBJsG3z2XMdZRW7bkiyF9noV50tVaLYcQ2ZB1k%2BZ5jol4j31RP2sm5SRydpvq4XDnH%2B1LwtxaxFd0&from=mpc_mz_and_flyme");
	}
	public boolean handleBackPressed(){
		if(canGoBack()){
			goBack();
			return true;
		}
		return false;
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void enableJs(){
		getSettings().setJavaScriptEnabled(true);
		
		// FIXME test 360
		addJavascriptInterface(new ClientObject(), "Client");
		
		addJavascriptInterface(new MyJsLocalObject(), "MyJsLocalObject");
		
		setWebViewClient(new MyWebViewClient());
		setWebChromeClient(new MyWebChromClient());
		
		
		// 适应屏幕
		getSettings().setUseWideViewPort(true);
		getSettings().setLoadWithOverviewMode(true);
		
		// 缩放
		getSettings().setSupportZoom(true);
		getSettings().setBuiltInZoomControls(true);
	}
	
	// FIXME test 360
	protected class ClientObject{
		@JavascriptInterface
		public void fillProfileSuccess(){
			Log.e(TAG, "fillProfileSuccess----------------");
			AlertDialog.Builder builder = new AlertDialog.Builder(JsWebView.this.getContext());
			builder.setTitle("弹出的title");
			builder.setPositiveButton(R.string.hello, null);
			builder.show();
		}
	}
	
	protected class MyJsLocalObject{
		@JavascriptInterface
		public void showMsg(final String msg){
			post(new Runnable() {
				public void run() {
					AlertDialog.Builder builder = new AlertDialog.Builder(JsWebView.this.getContext());
					builder.setTitle(msg);
					builder.setPositiveButton(R.string.hello, null);
					builder.show();
					loadUrl("javascript:jsFunction()");
				}
			});
		}
		// 检查加载到的source内容
		@JavascriptInterface
		public void checkSource(String source){
			Log.e(TAG, "source : " + source);
			int index = source.indexOf("mz_ic_accounts_flyme_logo_big.png");
			if(index != -1){
				post(new Runnable() {
					@Override
					public void run() {
						AlertDialog.Builder builder = new AlertDialog.Builder(JsWebView.this.getContext());
						builder.setTitle("get it!");
						builder.setPositiveButton(R.string.hello, null);
						builder.show();
					}
				});
			}
		}
	}
	
	private class MyWebViewClient extends WebViewClient{

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.e(TAG, "onPageStarted : " + url);
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.e(TAG, "onPageFinished : " + url);
			// 检查加载到的source内容
			view.loadUrl("javascript:window.MyJsLocalObject.checkSource('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
		}
	}
	
	private class MyWebChromClient extends WebChromeClient{

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			Log.e(TAG, "onProgressChanged : " + newProgress);
			super.onProgressChanged(view, newProgress);
		}
		
		@Override
		public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
			Log.e(TAG, "onJsConfirm : " + message);
			return super.onJsConfirm(view, url, message, result);
		}

		@Override
		public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
			Log.e(TAG, "onJsPrompt : " + message);
			return super.onJsPrompt(view, url, message, defaultValue, result);
		}


		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			Log.e(TAG, "onJsAlert : " + message);
			return super.onJsAlert(view, url, message, result);
		}
	}
}
